var modifyOrAddFlag;
//初始化数据
var cycleData = [{
		id:'',
		name:'全部'
	},{
		id:'once',
		name:'运行一次'
	},{
		id:'cycle',
		name:'定时运行'
	}];
$(document).ready(function(){
		// 存放选中的调度的领域接口的URL
		window.systemInterfaceUrl = null;
		// 存放选中的调度的运行状态
		window.runStatus = null;
	
		$('#win').window('close');
		//所属领域下拉框
		$('#comboxSearchfieldName').combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllOfCurrentUserCanManage' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable: false,
		    method:'get',
		    loadFilter: function(data){
		    	var allCheck = {'id':'','name':'全部'};
		    	data.content.unshift(allCheck);
		    	return data.content;
		    },
		    onSelect: function(record){
		    	comboxSearchSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
					data:'',
        		    loadFilter: function(data){
        		    	var allCheck = {'id':'','name':'全部'};
        		    	data.content.unshift(allCheck);
        		    	return data.content;
        		    },
        		    onLoadSuccess:function(){
        		    	comboxSearchSystemName.combobox('setValue','');
        		    }
                }).load();
		    },
		    onLoadSuccess:function(){
		    	$('#comboxSearchfieldName').combobox('setValue','');
		    }
		});
		//所属系统下拉框
		var comboxSearchSystemName = $('#comboxSearchSystemName').combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable: false,
		  data:[{id:'',name:'全部','selected':'true'}]
        });
		//周期下拉框
		$('#comboxSearchCycle').combobox({
			valueField:'id',
			textField:'name',
			editable: false,
			data:cycleData
		});
		$('#comboxFieldName').combobox({
			url: BASE_URL_FIELD_SEARCH + '/findAllOfCurrentUserCanManage' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'name',
		    editable:false,
		    method:'get',
		    loadFilter: function(data){
		    	var allCheck = {'id':'','name':'请选择'};
		    	if(data.content)
		    	{
		    		data.content.unshift(allCheck);
		    	}
		    	else
		    	{
		    		return data;
		    	}
		    	return data.content;
		    },
		    onSelect: function(record){
		    	comboxSystemName.combobox({
                    disabled: false,
                    method:'get',
                    queryParams: {fieldId: record.id},
                    url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
                    valueField: 'id',
                    textField: 'name',
					data:'',
        		    loadFilter: function(data){
        		    	
        		    	var allCheck = {'id':'','name':'请选择'};
        		    	data.content.unshift(allCheck);
        		    	return data.content;
        		    },
        		    onSelect: function(record){
        		    	comboxInterface.combobox({
                            disabled: false,
                            method:'get',
                            queryParams: {fieldSystemId: record.id},
                            url: BASE_URL_SYSTEM_INTERFACE_SEARCH +'/findByOwnerFieldSystem_Id' + '?v=' + Math.random(),
                            valueField: 'id',
                            textField: 'jobName',
        					data:'',
                		    loadFilter: function(data){
                		    	if(data[0].id == ""){
                		    		return data;
                		    	}
                		    	var allCheck = {'id':'','jobName':'请选择'};
	                		    data.unshift(allCheck);
	                		    return data;
                		    	
                		    },
                		    onLoadSuccess:function(){
                		    	$('#comboxInterface').combobox('setValue','');
                		    }
                        });
        		    },
        		    onLoadSuccess:function(){
        		    	$('#comboxInterface').combobox('setValue','');
        		    	
        		    }
                }).load();
		    	comboxInterface.combobox({
		    		disabled: true,
		            valueField: 'id',
		            textField: 'jobName',
		            editable: false,
		            url:'',
					data:[],
					loadFilter:function(data){
						var allCheck = {id:'',jobName:'请选择','selected':'true'};
						data.unshift(allCheck);
						return data;
					}
                });
		    }
		    
		});
		
		
		var comboxSystemName = $('#comboxSystemName').combobox({
            disabled: true,
            valueField: 'id',
            textField: 'name',
            editable:false,
			url:'',
			data:[],
			loadFilter:function(data){
				var allCheck = {id:'',name:'请选择','selected':'true'};
				data.unshift(allCheck);
				return data;
			}
		  	
        });
		
		//所属系统下的所有接口
		var comboxInterface = $('#comboxInterface').combobox({
			disabled: true,
            valueField: 'id',
            textField: 'jobName',
            editable: false,
            url:'',
			data:[],
			loadFilter:function(data){
				var allCheck = {id:'',jobName:'请选择','selected':'true'};
				data.unshift(allCheck);
				return data;
			}
		})
		
		$('#comboxExecutionCycleTime').combobox({
			url: BASE_URL_DATA_DICTIONARY_VALUE_SEARCH +'/findByTypeCode?typeCode='+DDTC_KETTLE_JOB_SCHEDULE_CYCLE_UNIT + '&v=' + Math.random(),
			valueField: 'valueCode',
		    textField: 'valueName',
		    editable:false,
		    method:'get',
		    loadFilter:function(data){
		    	return data;
		    },
		    onChange:function(e){
		    	var chooseVal = $("#comboxExecutionCycleTime").combobox('getValue');
				var cycleNum = $('#txtExecutionCycleNumber').val();
				if(chooseVal == "5" && cycleNum == "1")
				{
					$(".daySel, .txtEvery, .text_tips, #end_time_li").show();
				}else if(chooseVal == "1")
				{
					$(".txtEvery, .daySel, .text_tips, #end_time_li").hide();
				}else
				{
					$(".txtEvery, .text_tips, #end_time_li").show();
					$(".daySel").hide();
				}
		    }
		    
		});
		$('#comboxExecutionsendEmailType').combobox({
			url: BASE_URL_DATA_DICTIONARY_VALUE_SEARCH +'/findByTypeCode?typeCode='+DDTC_ERROR_EMAIL_SEND_TYPE + '&v=' + Math.random(),
			valueField: 'valueCode',
		    textField: 'valueName',
		    editable:false,
		    method:'get',
		    loadFilter:function(data){
		    	return data;
		    },
		    onChange:function(e){
		    }
		    
		});
		
		
		$("#datagrid").datagrid({
			url : BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/findByExample?v='+Math.random(),
			method:'get',
			autoRowHeight:true,
			singleSelect:true,
			striped:true,
			nowrap:false,
			pageSize:20,
			pageList:[10,20,50,100],
			columns:[[
						{field:'',width:10,checkbox:true},
						{field:'fieldName',title:'领域',width:80},
						{field:'fieldSystemName',title:'系统',width:70},
						{field:'name',title:'调度名',width:100,align:'left'},
						{field:'interfaceName',title:'接口',width:115,align:'left'},
						{field:'cycleForDisplay',title:'周期',width:40},
						{field:'runStatusForDisplay',title:'状态',width:40},
						{field:'beginTime',title:'调度开始时间',width:100},
						{field:'endTime',title:'调度结束时间',width:100},
						{field:'lastRunTime',title:'上一次执行时间',width:100},
						{field:'nextRunTime',title:'下一次执行时间',width:100},
						{field:'errSendTo',title:'错误通知人',width:155,
							/*formatter: function(value,row,index){
								var erroTo="";
								if(value != ""){
									var jons = JSON.parse(value);
									for(var i = 0;i < jons.length;i++){
										erroTo += (erroTo?";":"") +jons[i].emailAddress;
									}
								}
								return erroTo;
							}*/
						},
						{field:'remark',title:'备注',width:110,align:'left'}
			      ]],
			pagination:true,
			onSelect:function(rowIndex,rowData){
				if(rowData.runStatusForDisplay == "暂停")
				{
					$(".startOrStop .l-btn-text").text("重启");
					$(".startOrStop .icon-more").css("background","url(../../images/icons/restart.png) no-repeat center center"); 
				}else if(rowData.runStatusForDisplay == "正常")
				{
					$(".startOrStop .l-btn-text").text("暂停");
					$(".startOrStop .icon-more").css("background","url(../../images/icons/stop.png) no-repeat center center"); 
				}
				$("#toolbar_edit").linkbutton('enable');
				$("#toolbar_delete").linkbutton('enable');
			},
			onUnselect:function()
			{
				$(".startOrStop .l-btn-text").text("暂停/重启");
				$(".startOrStop .icon-more").css("background","url(../../images/icons/more.png) no-repeat center center"); 
			},
			loadFilter:function(data){
				//alert("inData:"+JSON.stringify(data));
				return {
					total: data.totalElements,
					rows: data.content
				};
			},
			onBeforeLoad:function(param){
				param.page -= 1;
				param.size = param.rows;
				delete param.rows;
				
				param.sort = 'createTime,desc';
				var fieldId = $('#comboxSearchfieldName').combobox('getValue');
				if(fieldId !=""){
					param.fieldId = fieldId;
				}
				
				var fieldSystemId = $('#comboxSearchSystemName').combobox('getValue');
				if(fieldSystemId !=""){
					param.fieldSystemId = fieldSystemId;
				}
				var runWay = $('#comboxSearchCycle').combobox('getValue');
				if(runWay !=""){
					param.runWay = runWay;
				}
				 
				var name = $('#txtSearchInterfaceName').val();
				if(name !=""){
					param.name = name;
				}
			}
		});
		
		$("#datagrid").datagrid('getPager').pagination({   
		    displayMsg:'当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
		}); 
		
	$(".button_con a" ).removeClass("l-btn-plain");
	
	
	//错误通知者选择
	$('#errNotif_selection').window({
		width:360,
		height:290,
		modal:true,
		minimizable:false,
		maximizable:false,
		collapsible:false
	});
	$('#errNotif_selection').window('close');  //关闭窗口	
	$('#selErrorNotification').click(function(e) {
		$("#errorNotification").val("");
		$.ajax({
			url:BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/getUserEmail?v=' + Math.random(),
			type:'get',
			success:function(data){
				var emailConHtml = "";
				//alert(data[0].userCode);
				for(var i = 0; i < data.length; ++i)
				{
					emailConHtml += '<li>' + 
										'<label><input type="checkbox" data-userCode="'+data[i].userCode+'" name="errNotifEmail" class="tree-checkbox" />' +
										'<span>'+data[i].userCode  + '</span>'+'---'+ data[i].emailAddress +
										'</label>' +
									'</li>';
				}
		    	$("#errNotif_selection ul").html(emailConHtml);
		    	var errSendTo = $("#txtErrorNotification").val();
		    	var errArray = errSendTo.split(";");
		    	//alert(errArray.length);
		    	for(var i = 0;i < errArray.length;i++){
					$("#errNotif_selection span").each(function() {
						if(errArray[i] == $(this).text())
						{
							$(this).click();
						}
					});
		    	}
				$("#errorInfo").scrollTop(0);
			}
		});
		
		
		$("input[name=errNotifEmail]").removeAttr("checked");
		$('#errNotif_selection').window('open');
		return false;
	});
	
	$("#searchConfirmErremail").click(function(e){
		choose_tree();
	});
	
	//定位显示
	var arrayLi = [];
	var arrayLiInd = 0;
	
	$("#errorNotification").bind('input propertychange', function() {
		arrayLi = [];
		arrayLiInd = 0;
		if($("#errorNotification").val() != '')
		{
			choose_tree();
		}else
		{
			var row = $('#errorInfo li');  
			row.removeClass('hover'); 
			$("#errorInfo").scrollTop(0);
		}
	});
	$(document , "#errorNotification").keyup(function(event){
	  if(event.keyCode ==13){
	    $("#searchConfirmErremail").trigger("click");
	  }
	});
	function choose_tree()
	{
		
		if(arrayLi.length == 0 && arrayLiInd == 0)
		{
			var searchVal = $("#errorNotification").val().toLowerCase(); 
			var rowcolumn = $('#errorInfo li');  
			var i = 0, j = 0;
			rowcolumn.removeClass('hover');  
			rowcolumn.each(function (column) {  
				var matchVal = $(this).text(); 
				
				if(matchVal.indexOf(searchVal) != -1)
				{
					i++;
					
					var panel_top = parseInt($(this).parents(".panel").css("top"));
					if(i <= 1)
					{
						$(this).addClass('hover'); 
						var top = $("#errorInfo").scrollTop() + $(this).offset().top - 70 - panel_top;
						$("#errorInfo").scrollTop(top);
					}else
					{				
						arrayLi.push([matchVal,$("#errorInfo").scrollTop() + $(this).offset().top - 70 - panel_top]);
					}
					
				}
			}); 
			
		}else
		{
			var row = $('#errorInfo li');  
			var rowcolumn = $('#errorInfo li');  
			rowcolumn.removeClass('hover');  
			if(arrayLiInd <  arrayLi.length)
			{
				rowcolumn.each(function (column) {  
					var matchVal = $(this).text(); 
					if(matchVal == arrayLi[arrayLiInd][0])
					{
						$(this).addClass('hover'); 
						$("#errorInfo").scrollTop(arrayLi[arrayLiInd][1]);
						arrayLiInd++;
						return false;
					}
				});
			}else
			{
				arrayLi = [];
				arrayLiInd = 0;
				$("#errorInfo").scrollTop(0);
			}
		}
	}
	
	$("#confirmErremail").click(function(e) {
		var len=$("input[name=errNotifEmail]:checked").length;
		if(len > 5){
			$.messager.alert('警告', '<p>最多只能选择五个错误通知者</p>', 'warning');
			return;
		}
		var sfruit = "";
		//var jsonErrorTo=[];
		//var selectLength = $("input[name=errNotifEmail]:checked").length;
		//var reg=new RegExp("'","g"); 
		//var i = 0;
		$("input[name=errNotifEmail]:checked").each(function(){
			   
				/*sfruit += (sfruit?";":"")+$(this).next().text()
				   if(i==0){
					   jsonErrorTo+="[";
				   }else {
					   jsonErrorTo+=",";
				   }
				
				  
					jsonErrorTo+="{\"id\":\""+$(this).data("id")+
					 "\",\"emailAddress\":\""+$(this).next().text()+
					 "\"}";
					
					
						   if(i==selectLength-1){
							   jsonErrorTo+="]";
						   }
					 
				
				i = i+1;*/
			//alert($(this).attr("data-userCode"));
			sfruit += (sfruit?";":"")+$(this).attr("data-userCode");
		});
			
		
		$("#txtErrorNotification").val("").val(sfruit);
		//$("#errorNotificationIds").val("").val(jsonErrorTo);
		$('#errNotif_selection').window('close'); 
	});
	
//===========================================================================================================================
	
	//错误通知者选择
	$('#errNotif_selectionfail').window({
		width:360,
		height:290,
		modal:true,
		minimizable:false,
		maximizable:false,
		collapsible:false
	});
	$('#errNotif_selectionfail').window('close');  //关闭窗口	
	$('#selErrorNotificationfail').click(function(e) {
		$("#errorNotificationfail").val("");
		$.ajax({
			url:BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/getUserEmail?v=' + Math.random(),
			type:'get',
			success:function(data){
				var emailConHtml = "";
				//alert(data[0].userCode);
				for(var i = 0; i < data.length; ++i)
				{
					emailConHtml += '<li>' + 
										'<label><input type="checkbox" data-userCode="'+data[i].userCode+'" name="errNotifEmailfail" class="tree-checkbox" />' +
										'<span>'+data[i].userCode  + '</span>'+'---'+ data[i].emailAddress +
										'</label>' +
									'</li>';
				}
		    	$("#errNotif_selectionfail ul").html(emailConHtml);
		    	var errSendTo = $("#txtErrorNotificationfail").val();
		    	var errArray = errSendTo.split(";");
		    	//alert(errArray.length);
		    	for(var i = 0;i < errArray.length;i++){
					$("#errNotif_selectionfail span").each(function() {
						if(errArray[i] == $(this).text())
						{
							$(this).click();
						}
					});
		    	}
				$("#errorInfofail").scrollTop(0);
			}
		});
		
		
		$("input[name=errNotifEmailfail]").removeAttr("checked");
		$('#errNotif_selectionfail').window('open');
		return false;
	});
	
	$("#searchConfirmErremailfail").click(function(e){
		choose_treefail();
	});
	
	//定位显示
	var arrayLi = [];
	var arrayLiInd = 0;
	
	$("#errorNotificationfail").bind('input propertychange', function() {
		arrayLi = [];
		arrayLiInd = 0;
		if($("#errorNotificationfail").val() != '')
		{
			choose_treefail();
		}else
		{
			var row = $('#errorInfofail li');  
			row.removeClass('hover'); 
			$("#errorInfofail").scrollTop(0);
		}
	});
	$(document , "#errorNotificationfail").keyup(function(event){
	  if(event.keyCode ==13){
	    $("#searchConfirmErremailfail").trigger("click");
	  }
	});
	function choose_treefail()
	{
		
		if(arrayLi.length == 0 && arrayLiInd == 0)
		{
			var searchVal = $("#errorNotificationfail").val().toLowerCase(); 
			var rowcolumn = $('#errorInfofail li');  
			var i = 0, j = 0;
			rowcolumn.removeClass('hover');  
			rowcolumn.each(function (column) {  
				var matchVal = $(this).text(); 
				
				if(matchVal.indexOf(searchVal) != -1)
				{
					i++;
					
					var panel_top = parseInt($(this).parents(".panel").css("top"));
					if(i <= 1)
					{
						$(this).addClass('hover'); 
						var top = $("#errorInfofail").scrollTop() + $(this).offset().top - 70 - panel_top;
						$("#errorInfofail").scrollTop(top);
					}else
					{				
						arrayLi.push([matchVal,$("#errorInfofail").scrollTop() + $(this).offset().top - 70 - panel_top]);
					}
					
				}
			}); 
			
		}else
		{
			var row = $('#errorInfofail li');  
			var rowcolumn = $('#errorInfofail li');  
			rowcolumn.removeClass('hover');  
			if(arrayLiInd <  arrayLi.length)
			{
				rowcolumn.each(function (column) {  
					var matchVal = $(this).text(); 
					if(matchVal == arrayLi[arrayLiInd][0])
					{
						$(this).addClass('hover'); 
						$("#errorInfofail").scrollTop(arrayLi[arrayLiInd][1]);
						arrayLiInd++;
						return false;
					}
				});
			}else
			{
				arrayLi = [];
				arrayLiInd = 0;
				$("#errorInfofail").scrollTop(0);
			}
		}
	}
	
	$("#confirmErremailfail").click(function(e) {
		var len=$("input[name=errNotifEmailfail]:checked").length;
		if(len > 5){
			$.messager.alert('警告', '<p>最多只能选择五个邮件失效通知者</p>', 'warning');
			return;
		}
		var sfruit = "";
		//var jsonErrorTo=[];
		//var selectLength = $("input[name=errNotifEmail]:checked").length;
		//var reg=new RegExp("'","g"); 
		//var i = 0;
		$("input[name=errNotifEmailfail]:checked").each(function(){
			   
				/*sfruit += (sfruit?";":"")+$(this).next().text()
				   if(i==0){
					   jsonErrorTo+="[";
				   }else {
					   jsonErrorTo+=",";
				   }
				
				  
					jsonErrorTo+="{\"id\":\""+$(this).data("id")+
					 "\",\"emailAddress\":\""+$(this).next().text()+
					 "\"}";
					
					
						   if(i==selectLength-1){
							   jsonErrorTo+="]";
						   }
					 
				
				i = i+1;*/
			//alert($(this).attr("data-userCode"));
			sfruit += (sfruit?";":"")+$(this).attr("data-userCode");
		});
			
		
		$("#txtErrorNotificationfail").val("").val(sfruit);
		//$("#errorNotificationIds").val("").val(jsonErrorTo);
		$('#errNotif_selectionfail').window('close'); 
	});
	
	$('#txtExecutionCycleNumber').bind('input propertychange', function() {
		var chooseVal = $("#comboxExecutionCycleTime").combobox('getValue');
		var cycleNum = $('#txtExecutionCycleNumber').val();
    	if(chooseVal == "5" && cycleNum == "1")
		{
			$(".daySel").show();
		}else{
			$(".daySel").hide();
		}
	});
	

	
	$("#toolbar_add").click(function(e) {
		 $("body").css("overflow-x","hidden");
	});
	
	$(".panel-tool-close, #instance_cancel").click(function(e) {
		$("body").css("overflow-x","inherit")
	});


	//清空接口内容
	$("#clearInterface").click(function(e) {
		$("#txtInterface").val('');
		$(this).css("display","none");
		return false;
	});
	
	
	
});


	
	function add(){
		modifyOrAddFlag = true;
		$('#addForm')[0].reset();
		$("#clearInterface").css("display","none");
		$('input[name=qx]').attr('checked',true);
		var data = $('#comboxFieldName').combobox('getData');	
		$("#comboxFieldName").combobox('setValue',data[0].id);
		
		
		setTimeout(function(){
			$("#comboxFieldName").siblings(".textbox").children(".textbox-text").val($("#comboxFieldName").combobox('getText'));
			$('#comboxSystemName').combobox({
				disabled: true,
				valueField: 'id',
				textField: 'name',
				editable:false,
				url:'',
				data:[],
				loadFilter:function(data){
					var allCheck = {id:'',name:'请选择','selected':'true'};
					data.unshift(allCheck);
					return data;
				}
			});
			$('#comboxInterface').combobox({
		    		disabled: true,
		            valueField: 'id',
		            textField: 'jobName',
		            editable: false,
		            url:'',
					data:[],
					loadFilter:function(data){
						var allCheck = {id:'',jobName:'请选择','selected':'true'};
						data.unshift(allCheck);
						return data;
					}
                });
		},50);
		
		var cycleTimeData = $('#comboxExecutionCycleTime').combobox('getData');
		$("#comboxExecutionCycleTime").combobox('setValue',cycleTimeData[4].valueCode);
		
		var sendEmailType = $('#comboxExecutionsendEmailType').combobox('getData');
		$("#comboxExecutionsendEmailType").combobox('setValue',sendEmailType[0].valueCode);
		
		setTimeout(function(){
			$("#comboxExecutionsendEmailType").siblings(".textbox").children(".textbox-text").val($("#comboxExecutionsendEmailType").combobox('getText'));
		},50);
		setTimeout(function(){
			$("#comboxExecutionCycleTime").siblings(".textbox").children(".textbox-text").val($("#comboxExecutionCycleTime").combobox('getText'));
		},50);
		
		
		/*
		
		setTimeout(function(){
			$("#comboxSystemName").siblings(".textbox").children(".textbox-text").val($("#comboxSystemName").combobox('getText'));
		},50);*/

		
		$('#txtStartTime').datetimebox('setValue', Date.parse(new Date()).toString());
		setTimeout(function(){
			$("#txtStartTime").siblings(".textbox").children(".textbox-text").val($("#txtStartTime").combobox('getText'));
		},50);
		
		$('#txtEndTime').datetimebox('setValue', '2020-01-01 00:00:00');
		setTimeout(function(){
			$("#txtEndTime").siblings(".textbox").children(".textbox-text").val($("#txtEndTime").combobox('getText'));
		},50);
		$("#comboxInterface").combobox({
			disabled:false
		});
		$("#comboxFieldName").combobox({
			disabled:false
		});
		$("#comboxSystemName").combobox({
			disabled:false
		});
		$('#win').window('setTitle','数据库接口调度管理-新增');
		$('#win').window('open');
	}
	
	function update(){
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert('警告',"<p>请选中要修改的记录!</p>","warning");
		}else{
			modifyOrAddFlag = false;
			
			$.ajax({
				url:BASE_URL_INTERFACE_SCHEDULE_CRUD + '/' + row.id + '?v=' + Math.random(),
				type:'get',
				success:function(dataSchedule){
					$('#comboxSystemName').combobox({
						disabled: true,
						method:'get',
						queryParams: {fieldId: dataSchedule.fieldId},
						url: BASE_URL_FIELD_SYSTEM_SEARCH +'/findByFieldOfCurrentUserCanManage' + '?v=' + Math.random(),
						valueField: 'id',
						textField: 'name',
						data:'',
						loadFilter: function(data){
							var allCheck = {'id':'','name':'请选择'};
							data.content.unshift(allCheck);
							return data.content;
						},
						onSelect: function(record){
							$('#comboxInterface').combobox({
	                            disabled: false,
	                            method:'get',
	                            queryParams: {fieldSystemId: record.id},
	                            url: BASE_URL_SYSTEM_INTERFACE_SEARCH +'/findByOwnerFieldSystem_Id' + '?v=' + Math.random(),
	                            valueField: 'id',
	                            textField: 'jobName',
	        					data:'',
	                		    loadFilter: function(data){
	                		    	if(data[0].id == ""){
	                		    		return data;
	                		    	}
	                		    	var allCheck = {'id':'','jobName':'请选择'};
		                		    data.unshift(allCheck);
		                		    return data;
	                		    	
	                		    },
	                		    onLoadSuccess:function(){
	                		    	$('#comboxInterface').combobox('setValue','');
	                		    }
	                        });
	        		    }
					}).load();
					$("#comboxFieldName").combobox('setValue',dataSchedule.fieldId);
					$("#comboxFieldName").siblings(".textbox").children(".textbox-text").val($("#comboxFieldName").combobox('getText'));
					$("#comboxSystemName").combobox('setValue',dataSchedule.fieldSystemId);
					$("#comboxSystemName").siblings(".textbox").children(".textbox-text").val($("#comboxSystemName").combobox('getText'));

					
					
					var fieldSystemId = $("#comboxSystemName").combobox('getValue');
					$('#comboxInterface').combobox({
                        disabled: true,
                        method:'get',
                        queryParams: {fieldSystemId: fieldSystemId},
                        url: BASE_URL_SYSTEM_INTERFACE_SEARCH +'/findByOwnerFieldSystem_Id' + '?v=' + Math.random(),
                        valueField: 'id',
                        textField: 'jobName',
    					data:'',
            		    loadFilter: function(data){
            		    	if(data[0].id == ""){
            		    		return data;
            		    	}
            		    	var allCheck = {'id':'','jobName':'请选择'};
                		    data.unshift(allCheck);
                		    return data;
            		    	
            		    },
            		    onLoadSuccess:function(){
            		    }
                    });
					
					$("#txtSchedulingName").val(dataSchedule.name);
					setTimeout(function(){
						$("#comboxInterface").combobox('setValue',dataSchedule.systemInterfaceId);
						$("#comboxInterface").siblings(".textbox").children(".textbox-text").val($("#comboxInterface").combobox('getText'));
					},200);
					if(dataSchedule.interfaceName !=='')
					{
						$("#clearInterface").css("display","block");
					}
					/*var errSendTo = dataSchedule.errSendTo;
					if(errSendTo != ""){
						$("#errorNotificationIds").val(erroTo);
						var jons = JSON.parse(errSendTo);
						var erroTo="";
						for(var i = 0;i < jons.length;i++){
							erroTo += (erroTo?";":"") +jons[i].emailAddress;
							
						}
					}*/
					$("#txtErrorNotification").val(dataSchedule.errSendTo);
					if(dataSchedule.dayOfWeek){
						var dayOfWeekCheck = dataSchedule.dayOfWeek.split(',');
						for(var i = 0;i < dayOfWeekCheck.length;i++){
 							$("input:checkbox[value='" + dayOfWeekCheck[i] + "']").attr('checked','true');
						}
					}

					$("#txtExecutionCycleNumber").val(dataSchedule.runCyc);
					$("#comboxExecutionCycleTime").combobox('setValue',dataSchedule.runWay);
					$("#txtStartTime").datetimebox('setValue',dataSchedule.beginTime);
					$("#txtEndTime").datetimebox('setValue',dataSchedule.endTime);
					$("#txtAreaDescription").val(dataSchedule.remark);
					$("#comboxExecutionCycleTime").val(dataSchedule.systemInterfaceName);
					$("#overTimeSetting").val(dataSchedule.overTimes);
					$("#comboxExecutionsendEmailType").combobox('setValue',dataSchedule.sendEmailType);
					$("#txtErrorNotificationfail").val(dataSchedule.errSendToFail);
					$("#isAgainExecutJob").val(dataSchedule.isAgainExecutJob);
					$("#maxSendEmailNum").val(dataSchedule.maxSendEmailNum);
					$("#failedNum").val(dataSchedule.failedNum);
					window.runStatus = dataSchedule.runStatus;
					
					$.ajax({
						url:dataSchedule._links.systemInterface.href,
						type:'get',
						success:function(dataInterface){
							window.systemInterfaceUrl = dataInterface._links.self.href;
						}
					});
					$('#win').window('setTitle','数据库接口调度管理-修改');
					$('#win').window('open');
					/*$("#comboxInterface").combobox({
						disabled:true
					});
					alert(JSON.stringify(dataSchedule));
					$("#comboxInterface").combobox("setValue",row.interfaceName);
					alert(row.interfaceName+"1");*/
					$("#comboxFieldName").combobox({
						disabled:true
					});
					$("#comboxFieldName").combobox("setValue",row.fieldId);
					/*$("#comboxSystemName").combobox({
						disabled:true
					});
					$("#comboxSystemName").combobox("setValue",row.fieldSystemName);*/
					
					
				},
				error:function(xhr,s,err){
					
				}
				
			});
		}
	}
	//先根据账号查询角色名称
   function	load1(){
	   $.ajax({
			type: "get",
			url: BASE_URL_USER_SEARCH +'/getCurrentUserInfo?v=' + Date.parse(new Date()),
			data: "",
			contentType: "application/json",
			success: function(result) {
				
				onSave(result.roleName);
			},
			error: function() {
				$.messager.alert('错误','<p>服务异常，获取当前用户信息失败!</p>', 'error');
			}
		});
   }
	//新增和修改保存
	function onSave(value){
		var dayOfWeek = $("input[name='qx']:checked").map(function () {
            return $(this).val();
        }).get().join(',');
		var row = $('#datagrid').datagrid('getSelected');
		var name = $("#txtSchedulingName").val();
		var runWay = $("#comboxExecutionCycleTime").combobox('getValue');
		var runCyc = $("#txtExecutionCycleNumber").val();
		var beginTime = $("#txtStartTime").datetimebox('getValue');
		var endTime = $("#txtEndTime").datetimebox('getValue');
		
	    //执行周期角色判断，
		if(runCyc <=30&& runWay =='3'&& value !='接口调度周期管理员'){
			$.messager.alert('警告', '<p>非执行角色"执行周期"设置不能小于30分钟</p>', 'warning');
			return;
		}else if(runCyc <=1800 && runWay =='2' && value !='接口调度周期管理员'){
			$.messager.alert('警告', '<p>非执行角色"执行周期"设置不能小于1800秒</p>', 'warning');
			return;
		}
		//alert(beginTime);
		if(beginTime == null || beginTime == ""){
			$.messager.alert('警告', '<p>开始时间不能为空</p>', 'warning');
			return;
		}
		if(runWay != 1){
			if(!comptime(beginTime,endTime)){
				$.messager.alert('警告', '<p>结束时间要大于开始时间</p>', 'warning');
				return;
			}
		}else{
			endTime = "";
		}
		if(runWay != 5){
			dayOfWeek = "";
		}else{
			if(dayOfWeek == "" || dayOfWeek == null){
				$.messager.alert('警告', '<p>请选择至少一个调度周期（周一到周日）再进行保存操作！</p>', 'warning');
				return;
			}
		}
		var remark = $("#txtAreaDescription").val();
		var errSendTo = $("#txtErrorNotification").val();
		var overTimes = $("#overTimeSetting").val();
		var id = $("#comboxInterface").combobox('getValue');
		var systemInterfaceId;
		if(id != "")
		{
			//window.systemInterfaceUrl = BASE_URL_SYSTEM_INTERFACE +'/'+id + '?v=' + Math.random();
			systemInterfaceId = id;
		}else
		{
			$.messager.alert('警告', '<p>接口不能为空，请选择接口!</p>', 'warning');
			return;
		}
		var sendEmailType = $("#comboxExecutionsendEmailType").combobox('getValue');
		var errSendToFail = $("#txtErrorNotificationfail").val();
		var maxSendEmailNum = $("#maxSendEmailNum").val();
		//var failedNum = $("#failedNum").val();
		var isAgainExecutJob = $("#isAgainExecutJob").val();
		/*
		alert("add"+$("#addForm").form("validate"));*/
		if($("#addForm").form("validate")){
			
			$("#instance_save").linkbutton("disable");
			$("#instance_save .l-btn-text").text("提交中...");
			if(!modifyOrAddFlag){
				var jsonData = {
						id:row.id,
						name:name,
						errSendTo:errSendTo,
						runWay:runWay,
						runCyc:runCyc,
						dayOfWeek:dayOfWeek,
						beginTime:beginTime,
						endTime:endTime,
						remark:remark,
						runStatus: window.runStatus,
						overTimes: overTimes,
						//systemInterface: window.systemInterfaceUrl
						systemInterfaceId: row.systemInterfaceId,
						sendEmailType:sendEmailType,
						errSendToFail:errSendToFail,
						maxSendEmailNum:maxSendEmailNum,
						//failedNum:failedNum,
						isAgainExecutJob:isAgainExecutJob
				};
				
				var jsonStr = JSON.stringify(jsonData);
				$.ajax({
					url:BASE_URL_INTERFACE_SCHEDULE_CRUD + '/addOrupdateInterfaceScheduling' + '?v=' + Math.random(),
					dataType:'json',
					type:'post',
					contentType:"application/json",
					data: jsonStr,
					success:function(result){
						if(result.backValue){
							$.messager.alert('提示',"<p>修改成功!</p>","info");
							$('#win').window('close');
							$("#datagrid").datagrid("reload",BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/findByExample?v='+Math.random());
						}
						else
						{	if(result.error=="2"){
								$.messager.confirm('提示',"<p>" + result.reason + "</p>", function(result) {
									if(result)
									{	
										jsonData.pass=true,
										$.ajax({
											url:BASE_URL_INTERFACE_SCHEDULE_CRUD + '/addOrupdateInterfaceScheduling' + '?v=' + Math.random(),
											dataType:'json',
											type:'post',
											contentType:"application/json",
											data: JSON.stringify(jsonData),
											success:function(result){
												$('#win').window('close');
												$("#datagrid").datagrid("reload",BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/findByExample?v='+Math.random());
												},
											});
									}else{
										jsonData.pass=false;
									}
								});
							}else{
								$.messager.alert('提示',"<p>" + result.reason + "</p>","info");
							}
						}
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
					},
					error:function(xhr,s,err){
						$.messager.alert("错误","<p>服务异常，修改信息失败，请重新登录或稍后再试！</p>","error");	
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
					}
					
					
				});
			}else{
				var jsonData = {
						name:name,
						errSendTo:errSendTo,
						runWay:runWay,
						runCyc:runCyc,
						dayOfWeek:dayOfWeek,
						beginTime:beginTime,
						endTime:endTime,
						remark:remark,
						runStatus: window.runStatus,
						overTimes: overTimes,
						//systemInterface: window.systemInterfaceUrl
						systemInterfaceId: systemInterfaceId,
						sendEmailType:sendEmailType,
						errSendToFail:errSendToFail,
						maxSendEmailNum:maxSendEmailNum,
						//failedNum:failedNum,
						isAgainExecutJob:isAgainExecutJob
				};
				
				var jsonStr = JSON.stringify(jsonData);
				$.ajax({
					url:BASE_URL_INTERFACE_SCHEDULE_CRUD + '/addOrupdateInterfaceScheduling' +'?v=' + Math.random(),
					type:'post',
					contentType:"application/json",
					data: jsonStr,
					timeout:30000,
					success:function(result){
						if(result.backValue){
							$.messager.alert('提示',"<p>新增成功!</p>","info");
							$('#win').window('close');
							$("#datagrid").datagrid("reload",BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/findByExample?v='+Math.random());
						}else{
							if(result.error=="2"){
								$.messager.confirm('提示',"<p>" + result.reason + "</p>", function(result) {
									if(result)
									{	
										jsonData.pass=true,
										$.ajax({
											url:BASE_URL_INTERFACE_SCHEDULE_CRUD + '/addOrupdateInterfaceScheduling' + '?v=' + Math.random(),
											dataType:'json',
											type:'post',
											contentType:"application/json",
											data: JSON.stringify(jsonData),
											success:function(result){
												$('#win').window('close');
												$("#datagrid").datagrid("reload",BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/findByExample?v='+Math.random());
												},
											});
									}else{
										jsonData.pass=false;
									}
								});
							}else{
								$.messager.alert('提示',"<p>" + result.reason + "</p>","info");
							}
						}
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
					},
					error:function(xhr,s,err){
						$.messager.alert("错误","<p>服务异常，新增失败，请重新登录或稍后再试！</p>","error");	
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
					}
				});
			}
		}
	}
	
	
	function del(){
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert('警告',"<p>请选中要删除的记录!</p>","warning");
			return;
		}
		var id = row.id;
 		var param = {id:id};
		//var delParam = {id:id};
		
		$.ajax({
			url:BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/checkScheduleStatus' + '?v=' + Math.random(),
			dataType:'json',
			type:'get',
			data:param,
			contentType:"application/json",
			success:function(result){
				if(result.isCanDelete){
					$.messager.confirm('温馨提示','<p>你真的要删除么?</p>',function(r){
		 				if (r){
						 		$.ajax({
									url:BASE_URL_INTERFACE_SCHEDULE_CRUD + '/deleteScheduling?id='+row.id+'&v=' + Math.random(),
									dataType:'json',
									type:'delete',
									contentType:"application/json",
									success:function(result){
										if(result.backValue){
											$.messager.alert('提示','<p>删除成功!</p>','info');
											$("#datagrid").datagrid("reload", BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/findByExample' + '?v=' + Math.random());
										}else{
											$.messager.alert('提示','<p>删除失败!</p>','info');
											$("#datagrid").datagrid("reload", BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/findByExample' + '?v=' + Math.random());
										}
									},
									error:function(){
										$.messager.alert("错误","<p>服务异常，删除失败，请重新登录或稍后再试！</p>","error");	
									}
						 		});
		 				}
		 			});
				}else{
					$.messager.alert('警告','<p>当前调度正在执行中，请稍后再操作</p>','warning');
				}
			},
			error:function(){
				$.messager.alert("错误","<p>服务异常，操作失败，请重新登录或稍后再试！</p>","error");	
			}
 		});
		
	}

	//查询
	function search(){
		$('#datagrid').datagrid('load');
	}
	//导出
	//暂停或重启
	function startOrStop(){
		var row = $('#datagrid').datagrid('getSelected');/*
		var id = row.id;
 		var param = {id:id};*/
		if(row == null){
			$.messager.alert('警告',"<p>请选中要暂停/重启的记录</p>","warning");
			return;
		}
		$.ajax({
			url:BASE_URL_INTERFACE_SCHEDULE_CRUD + '/changeScheduleStatus?id=' + row.id + '&v=' + Math.random(),
			dataType:'json',
			type:'post',
			contentType:"application/json",
			success:function(data){
				if(data.nowTheScheduleStatus=="On"){
					$.messager.alert('提示','<p>重启成功!</p>','info');
				}
				if(data.nowTheScheduleStatus=="Off"){
					$.messager.alert('提示','<p>暂停成功!</p>','info');
				}
				$("#datagrid").datagrid("reload", BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/findByExample' + '?v=' + Math.random());
			},
			error:function(){
				$.messager.alert("错误","<p>服务异常，操作失败，请重新登录或稍后再试！</p>","error");	
			}
 		});
	}
	//手动执行
	function manualExecution(){
		var row = $('#datagrid').datagrid('getSelected');/*
		var id = row.id;
 		var param = {id:id};*/
		if(row == null){
			$.messager.alert('警告',"<p>请选中要手动执行的记录!</p>","warning");
			return;
		}
		$.ajax({
			url:BASE_URL_KETTLE_JOB + '/runJobByInterfaceScheduleId',
			dataType:'json',
			type:'post',
			data: JSON.stringify({interfaceScheduleId: row.id}),
			contentType:"application/json",
			success:function(result){
				if(result.startSuccess){
					$.messager.alert('提示','<p>接口开始执行!</p>','info');
				}else{
					switch(result.errorCode){
					case 'RUNNING':
						$.messager.alert("错误","<p>接口正在执行中，请等待执行完毕！</p>","error");
						break;
					default:
						$.messager.alert("错误","<p>接口执行失败！</p>","error");
					}
				}
				$("#datagrid").datagrid("reload", BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/findByExample' + '?v=' + Math.random());
			},
			error:function(){
				$.messager.alert("错误","<p>服务异常，操作失败，请重新登录或稍后再试！</p>","error");	
			}
 		});
	}
	function rePage(){
		$('#win').window('close');
		$("#datagrid").datagrid("reload", BASE_URL_INTERFACE_SCHEDULE_SEARCH + '/findByExample?v='+Math.random());
	}
	function refresh(){
		$('#datagrid').datagrid('load');
	}
	